/*
 * 
 * Version 1.00
 * 
 * Created on 2007-6-4
 * Encoding GB2312
 */
package net.comm.group.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;

import net.comm.common.GlbFinal;
import net.comm.common.ReturnMessage;
import net.comm.oper.service.impl.OperLogServiceImpl;
import net.comm.oper.web.form.OperLogForm;
import net.comm.param.service.impl.SequenceMgr;
import net.comm.common.common;


import net.comm.group.bean.BaseGAlbum;
import net.comm.group.bean.BaseGPicture;
import net.comm.group.db.DbGAlbumService;
import net.comm.group.db.GAlbumServiceSqlMysql;
import net.comm.group.web.form.GAlbumForm;
import net.comm.group.web.form.GPictureForm;
import net.comm.group.web.form.GroupsForm;
import net.comm.page.PageCtr;

import net.comm.tags.JstlFun;
import net.comm.util.DatetimeUtil;
import net.comm.util.DbcpPool;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.sakaiproject.db.impl.BasicSqlService;


/**
 *
 * @author hcgong(hcgong@sina.com)
 * @version 1.0
 * @date 2007-6-4
 */
public class GAlbumServiceImpl {

	static Logger logger = Logger.getLogger(GAlbumServiceImpl.class.getName());

	/**
	 * 
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#list(net.swift.module.other.ExaQueryBean, net.swift.common.ReturnMessage)
	 */
	public List list(GAlbumForm theForm,  ReturnMessage msg) 
	{
		List list = null;

		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();

			Object[] fields2 = new Object[1];
			fields2[0] = theForm.getQryGroupID();
			/*
			 * 获得查询SQL语句
			 */
			String sql = servSql.getCountSql3();

			/**
			 * 根据SQL执行结果计算分页相关信息
			 */
			PageCtr page = theForm.getPage();
			page.setTotalNum(bSqlServ.dbCount(cn, sql, fields2));
			page.caculate();

			//取得FORM中传入的查询参数
			Object[] fields = new Object[3];
			
			fields[0] = theForm.getQryGroupID();
			fields[1] = page.getPos()-1;
			fields[2] = page.getPageSize();
			
			sql = servSql.getRecbyPageSql();

			list = bSqlServ.dbRead(cn, sql, fields, new DbGAlbumService());
			
		    DbcpPool.returnConnection(cn);
		    
		} catch(Exception ex) 
		{
			/**
			 * 记录相关日志
			 */
			logger.error(ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
			
		} finally {
			DbcpPool.returnConnection(cn);
		}		
		
		return list;
	}

	/**
	 * 返回根据会员ID查询的会员操作日志
	 */
	public List list(String  userID) 
	{
		List list = null;
		Connection cn = null;

		try
		{
			cn = DbcpPool.getConnection();
			
			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			
			fields[0] = userID;			

			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
						
			BasicSqlService  bSqlServ = new BasicSqlService();

			/*
			 * 获得查询SQL语句
			 */
			String sql = servSql.getByUserIDSql();
									
			list = bSqlServ.dbRead(cn, sql, fields, new DbGAlbumService());
									
		    DbcpPool.returnConnection(cn);
		    
		} catch(Exception ex) 
		{
			/**
			 * 记录相关日志
			 */
			logger.error(ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return list;
	}
	/**
	 * 
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#list(net.swift.module.other.ExaQueryBean, net.swift.common.ReturnMessage)
	 */
	public List adlist(GAlbumForm theForm,  ReturnMessage msg) 
	{
		List list = new Vector();

		Connection cn = null;
		Statement stmt=null;
		ResultSet rs=null;
		try
		{
			cn = DbcpPool.getConnection();
			
			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
			
			StringBuffer sb = new StringBuffer(" where 1=1");

			if(theForm.getQryGroupID() > 0){
				
				sb.append(" and GroupID = ");
				sb.append(theForm.getQryGroupID());
				sb.append(" ");
			}			
			if(theForm.getQryUserID() > 0){
				
				sb.append(" and userID = ");
				sb.append(theForm.getQryUserID());
				sb.append(" ");
			}

			String qryOrderby = theForm.getQryOrderby().replaceAll(GlbFinal.SQLINjection, " ");
			if(!qryOrderby.equals("")){
				
				sb.append(" Order by ");
				sb.append(qryOrderby);
				sb.append(" ");
				
			}else{
				sb.append(" Order by Ctime desc ");
			}
			
			
			//查询记录数
			stmt = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			String sql = servSql.getCountSql1();

			logger.debug(sql+sb.toString());
			rs=stmt.executeQuery(sql+sb.toString());
			int nRows = 0;
			if (rs.next())
	           nRows = rs.getInt("COUNT");
			else
			{
	            rs.close();
	            stmt.close();
	            DbcpPool.returnConnection(cn);
			    return list;
			}
			/**
			 * 根据SQL执行结果计算分页相关信息
			 */
			PageCtr page = theForm.getPage();
			page.setTotalNum(nRows);
			page.caculate();

			sb.append(" limit ");
			sb.append(page.getPos()-1);
			sb.append(", ");
			sb.append(page.getPageSize());
			
			 //取记录
			 sql = servSql.getRecSql();
			 logger.debug(sql+sb.toString());
			 DbGAlbumService dbservice = new DbGAlbumService();
			 
			 rs=stmt.executeQuery(sql+sb.toString());
			 while (rs.next())
			 {
				try
				{
					Object obj = dbservice.readSqlResultRecord(rs);
					if (obj != null) list.add(obj);
				}
				catch (Throwable t)
				{
					logger.error(t.getMessage());
				}		
			 }
			 rs.close();
			 stmt.close();
		     DbcpPool.returnConnection(cn);

		} catch(Exception ex) 
		{
			/**
			 * 记录相关日志
			 */
			logger.error(ex.getMessage());
			try {
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
				DbcpPool.returnConnection(cn);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}			
	    }finally {
			try {
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}			
			DbcpPool.returnConnection(cn);
		}		
		return list;
	}
	
	/**
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#get(net.swift.db.tab_paramnostro, net.swift.common.ReturnMessage)
	 */
	public void get(GAlbumForm theForm, ReturnMessage msg) 
	{
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			List list = null;

			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			fields[0] = theForm.getGalbumID();			
			
			String sql = servSql.getbykeySql();
					
			list = bSqlServ.dbRead(cn, sql, fields, new DbGAlbumService());
			if(list.size() == 0){
				common.setAppFailMsg(msg , " 取记录失败，请检查！");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			
			BaseGAlbum base = (BaseGAlbum)list.get(0);
				
			BeanUtils.copyProperties(theForm, base);
			
			DbcpPool.returnConnection(cn);
			return;
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about invite" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}
	/**
	 * 添加到表中
	 * @see net.IUserbasicService.module.other.IUserService#add(net.swift.common.ReturnMessage)
	 */
	public void add(GAlbumForm theForm,String path, ReturnMessage msg) 
	{
		
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			DbcpPool.beginTran(cn);

			add(cn , theForm,path, msg);
			if(msg.getErrCode() != 0){
				return;
			}
			
			DbcpPool.commitTran(cn);
			DbcpPool.closeTran(cn);
			DbcpPool.returnConnection(cn);

		} catch(Exception ex) 
		{
			common.setAppFailMsg(msg , ex.getMessage());
			logger.error("System error , param get about operlog" + ex);
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		return ;
	}
	/**
	 * 添加到表中
	 * @see net.IUserbasicService.module.other.IUserService#add(net.swift.common.ReturnMessage)
	 */
	public void add(Connection cn , GAlbumForm theForm,String path, ReturnMessage msg) 
	{
		
		try
		{
			//取得FORM中传入的查询参数
			Object[] fields = new Object[11];
			
			theForm.setGalbumID(SequenceMgr.generateSeq(GlbFinal.SEQ_INITDATE,GlbFinal.SEQ_GALBUMID));			
			
			fields[0] = theForm.getGalbumID();			
			fields[1] = theForm.getGroupID();
			fields[2] = theForm.getAlbumname();
			fields[3] = theForm.getAlbuminfo();
			fields[4] = theForm.getAfolder();
			fields[5] = theForm.getNum();
			fields[6] = theForm.getUserID();
			fields[7] = theForm.getProtect();
			fields[8] = theForm.getDelflg();
			fields[9] = DatetimeUtil.getDatetime();
			fields[10] = DatetimeUtil.getDatetime();
			
			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = servSql.getInsertSql();
						
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(!res){
				common.setAppFailMsg(msg , " 创建失败！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return ;
			}
			
			//更新群组参与值
			if(theForm.getGroupID() != GlbFinal.PUBLICID){
				GroupsServiceImpl groupservice = new GroupsServiceImpl();
				GroupsForm groupForm = new GroupsForm();
				
				groupForm.Clear();
				groupForm.setGroupID(theForm.getGroupID());
				groupForm.setPartakeVal(1);
				
				groupservice.updNum(cn, groupForm, msg);
				if(msg.getErrCode() != 0){
					
					return;
				}					
			}
			
			//添加用户动态表
			OperLogServiceImpl logservice = new OperLogServiceImpl();
			OperLogForm logForm = new OperLogForm();
			
			logForm.setUserID(theForm.getUserID());
			
			String[] arr = new String[7];
			arr[0] = JstlFun.GetUserNick(theForm.getUserID());			//主操作者		
			arr[1] = "";												//主动者与被动者的关系副词
			arr[2] = "";												//被动接受者ID
			arr[3] = "";												//被动接受者姓名
			if(theForm.getGroupID() != GlbFinal.PUBLICID){
				
				arr[4] = "新建部落相册：";									//操作
				logForm.setType(GlbFinal.OPERTYPE_GALBUM);					//群相册
			}else{
				
				arr[4] = "新建个人相册：";									//操作
				logForm.setType(GlbFinal.OPERTYPE_PERSONALBUM);					//个人相册
			}
			arr[5] = theForm.getAlbumname();								//操作对象名称
			arr[6] = String.valueOf(theForm.getGalbumID());					//操作对象KEY，多个字段以'|'分隔

			logForm.setLogarr(arr);
			
			logservice.add(cn, logForm, msg);
			if(msg.getErrCode() != 0){
				return;
			}				
			

		} catch(Exception ex) 
		{
			common.setAppFailMsg(msg , ex.getMessage());
			logger.error("System error , param get about operlog" + ex);
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
		}
		return ;
	}
	/**
	 * 删除一条指定记录
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void delete(GAlbumForm theForm, ReturnMessage msg) 
	{
		
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			DbcpPool.beginTran(cn);

			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();

			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			fields[0] = theForm.getGalbumID();			
			
			String sql = servSql.getbykeySql();
					
			List list = bSqlServ.dbRead(cn, sql, fields, new DbGAlbumService());
			if(list.size() == 0){
				common.setAppFailMsg(msg , " 取记录失败，请检查！");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			
			BaseGAlbum base = (BaseGAlbum)list.get(0);
				
			//读取相册的所有图片
			GPictureServiceImpl picservice = new GPictureServiceImpl();
			GPictureForm picform = new GPictureForm();
			
			picform.setQryGAlbumID(theForm.getGalbumID());
			
			List piclist = picservice.adlist(picform, msg);
			if(piclist.size() > 0){
				//删除所有照片及评论信息
				BaseGPicture picbase = null;
				
				int len = piclist.size();
				
				for(int i=0; i< len; i ++){
					picbase = (BaseGPicture)piclist.get(i);
					
					picform.Clear();
					picform.setGpicID(picbase.getGpicID());
					
					picservice.delete(cn, picform, msg);
					if(msg.getErrCode() != 0){
						return;
					}
				}
			}
			
			sql = servSql.getDeleteSql();
			
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(!res){
				common.setAppFailMsg(msg , " 删除记录失败，请检查！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;
			}			
			BeanUtils.copyProperties(theForm, base);
			
			DbcpPool.commitTran(cn);
			DbcpPool.closeTran(cn);
			DbcpPool.returnConnection(cn);
			return;
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about invite" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}
	/**
	 * 更新一条指定记录
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void updnum(Connection cn, GAlbumForm theForm, ReturnMessage msg) 
	{
		
		try
		{

			//取得FORM中传入的查询参数
			Object[] fields2 = new Object[1];
			fields2[0] = theForm.getGalbumID();			
			
			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = servSql.getbykeySql();
					
			List list = bSqlServ.dbRead(cn, sql, fields2, new DbGAlbumService());
			if(list.size() ==0){
				common.setAppFailMsg(msg , " 取记录失败，请检查！");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			BaseGAlbum base = (BaseGAlbum)list.get(0);
			
			//取得FORM中传入的查询参数
			Object[] fields = new Object[11];
			
			fields[0] = base.getGroupID();
			fields[1] = base.getAlbumname();
			fields[2] = base.getAlbuminfo();
			fields[3] = base.getAfolder();
			fields[4] = base.getNum() + theForm.getNum();//+1： 增加  -1：删除
			fields[5] = base.getUserID();
			fields[6] = base.getProtect();
			fields[7] = base.getDelflg();
			fields[8] = base.getCtime();
			fields[9] = DatetimeUtil.getDatetime();
			fields[10] = theForm.getGalbumID();
			
			sql = servSql.getUpdateSql();
						
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(!res){
				common.setAppFailMsg(msg , " 修改数量失败！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return ;
			}

		} catch(Exception ex) 
		{
			common.setAppFailMsg(msg , ex.getMessage());
			logger.error("System error , param get about operlog" + ex);
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		}
		
		return ;
	}
	
	
	/**
	 * 更新一条指定记录
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void update(GAlbumForm theForm, ReturnMessage msg) 
	{
		
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			DbcpPool.beginTran(cn);

			GAlbumServiceSqlMysql servSql = new GAlbumServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			//取得FORM中传入的查询参数
			Object[] fields2 = new Object[1];
			fields2[0] = theForm.getGalbumID();			
			
			String sql = servSql.getbykeySql();
					
			List list = bSqlServ.dbRead(cn, sql, fields2, new DbGAlbumService());
			if(list.size() ==0){
				common.setAppFailMsg(msg , " 取记录失败，请检查！");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			BaseGAlbum base = (BaseGAlbum)list.get(0);
			
			//取得FORM中传入的查询参数
			Object[] fields = new Object[11];
			
			fields[0] = theForm.getGroupID();
			fields[1] = theForm.getAlbumname();
			fields[2] = theForm.getAlbuminfo();
			fields[3] = theForm.getAfolder();
			fields[4] = theForm.getNum();
			fields[5] = theForm.getUserID();
			fields[6] = theForm.getProtect();
			fields[7] = theForm.getDelflg();
			fields[8] = theForm.getCtime();
			fields[9] = DatetimeUtil.getDatetime();
			fields[10] = theForm.getGalbumID();
			
			sql = servSql.getUpdateSql();
						
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(!res){
				common.setAppFailMsg(msg , " 修改失败！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return ;
			}
			DbcpPool.commitTran(cn);
			DbcpPool.closeTran(cn);
			DbcpPool.returnConnection(cn);

		} catch(Exception ex) 
		{
			common.setAppFailMsg(msg , ex.getMessage());
			logger.error("System error , param get about operlog" + ex);
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}

}
